package com.hs.hlw.credit.system.common.util;

import com.hualongdata.exception.BusinessException;
import com.jcraft.jsch.*;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.util.Properties;

public class SftpUtil {
    /**
     * 获取SFTP通道
     *
     * @param sftpDto
     * @return
     */
    private static ChannelSftp getSftp(SftpDto sftpDto) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(sftpDto.getUsername(), sftpDto.getHost(), sftpDto.getPort());
            session.setPassword(sftpDto.getPassword());

            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            throw new BusinessException("连接FTP服务器失败");
        }
        return sftp;
    }

    /**
     * 同时上传多个文件到FTP服务器
     *
     * @param sftpDto
     */
    public static boolean uploadFile(SftpDto sftpDto) {
        ChannelSftp sftp = getSftp(sftpDto);
        try {
            sftp.cd(sftpDto.getSftpPath());
            if (sftpDto.getSavePath().indexOf("/") == -1) {
                try {
                    sftp.cd(sftpDto.getSavePath());
                } catch (SftpException sException) {
                    sftp.mkdir(sftpDto.getSavePath());
                    sftp.cd(sftpDto.getSavePath());
                }
            } else {
                String[] pathArray = sftpDto.getSavePath().split("/");
                for (String path : pathArray) {
                    try {
                        if (StringUtils.isNotBlank(path)) {
                            sftp.cd(path);
                        }
                    } catch (SftpException sException) {
                        sftp.mkdir(path);
                        sftp.cd(path);
                    }
                }
            }
            sftp.put(sftpDto.getFileInputStream(), sftpDto.getFileName());
            sftpDto.setUploadSucceed(true);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (sftp != null) {
                sftp.disconnect();
            }
        }
        return true;
    }

    @Data
    public static class SftpDto {
        private InputStream fileInputStream;
        private String savePath;
        private String fileName;

        private String sftpPath;
        private String host;
        private Integer port;
        private String username;
        private String password;
        private boolean uploadSucceed;
        private boolean connected;
    }

    public static void main(String[] args) {
    }
}
